package com.hmjk.health.card;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.HttpConf;
import com.hmjk.health.home.DeviceManagerEdit;
import com.hmjk.health.setting.SettingActivity;
import com.hmjk.health.setting.SettingsConstants;
import com.hmjk.health.util.DEV_DATA;
import com.hmjk.health.util.DEV_SET;
import com.hmjk.health.util.QRCodeActivity;
import com.hmjk.health.views.PagerIndexStrip;
import com.hmjk.health.views.ViewsPagerAdapter;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class CardsActivity extends FragmentActivity implements OnClickListener, OnTouchListener, OnPageChangeListener{
	private final String TAG = CardsActivity.class.getSimpleName();
	private HealthApp mApp = null;
	private DEV_DATA mCurDev = null;
	
	private ProgressBar mLoadingProgress;
	
	private ViewPager mSlider;
	private FragmentStatePagerAdapter mAdapter;
	
	private TextView mName;
	private boolean loaded = false;
	private ArrayList<DEV_DATA> mDevListData = new ArrayList<DEV_DATA>();
	private ArrayList<CardFragment> mPages = new ArrayList<CardFragment>();
	private HashMap<String, CardFragment> mFragmentMap = new HashMap<String, CardFragment>();
	
	//menu views
	private View mInvokeMenu;
	private RelativeLayout mMenuBg;
	private RelativeLayout mMenu;
	private ViewPager mMenuPager;
	private PagerIndexStrip mMenuIndex;
	private Animation mUpAnim;
	//private Animation mUpAnim2;
	private static final String SENT_SMS_CMD_ACTION = "com.hmjk.sms.SmsSend";
	
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		logd("onCreate");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		
		Intent i = getIntent();
		
		String indicated = i.getStringExtra("indicated");
		mCurDev = new DEV_DATA();
		mCurDev.id = indicated.trim();
		
		setContentView(R.layout.cards_activity);
			
		ImageView back = (ImageView) findViewById(R.id.back);
		back.setOnClickListener(this);
		
		ImageView set = (ImageView) findViewById(R.id.set);
		set.setOnClickListener(this);
		
		mLoadingProgress = (ProgressBar) findViewById(R.id.loading_progress);
		mLoadingProgress.setVisibility(View.GONE);
		
		mAdapter = new FragmentStatePagerAdapter(getSupportFragmentManager()){

			@Override
			public Fragment getItem(int pos) {
				return mPages.get(pos);
			}

			@Override
			public int getCount() {
				return mPages.size();
			}
			
			@Override
			public int getItemPosition(Object object){
				return PagerAdapter.POSITION_NONE;
			}
		};
		mSlider = (ViewPager) findViewById(R.id.slider_pager);
		mSlider.setAdapter(mAdapter);
		mSlider.setOnPageChangeListener(this);
		mName = (TextView) findViewById(R.id.card_name);
		
		/* views for popmenu start */
		mInvokeMenu = findViewById(R.id.invoke_menu);
		mInvokeMenu.setOnTouchListener(this);
		
		mMenuBg = (RelativeLayout) findViewById(R.id.menu_bg);
		mMenu = (RelativeLayout) findViewById(R.id.menu);
		mMenuPager = (ViewPager) mMenu.findViewById(R.id.menu_pager);
		mMenuIndex = (PagerIndexStrip) mMenu.findViewById(R.id.menu_index);
		mMenuIndex.setResType(PagerIndexStrip.RES_TYPE_BLACK);
		mMenuIndex.setCount(2);
		mMenuIndex.setCurrent(0);
		mMenuPager.setOnPageChangeListener(new OnPageChangeListener(){

			@Override
			public void onPageScrollStateChanged(int arg0) {}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {}

			@Override
			public void onPageSelected(int pos) {
				mMenuIndex.setCurrent(pos);
				mMenuIndex.update();
			}
			
		});
		ArrayList<View> menuViews = new ArrayList<View>();
		LayoutInflater inflater = LayoutInflater.from(this);
		View page1 = inflater.inflate(R.layout.menu_page_1, null);
		View page2 = inflater.inflate(R.layout.menu_page_2, null);
		menuViews.add(page1);
		menuViews.add(page2);
		//ImageView msg = (ImageView) mMenu.findViewById(R.id.but_msg);
		ImageView calendar = (ImageView) page1.findViewById(R.id.but_calendar);
		ImageView invite = (ImageView) page1.findViewById(R.id.but_invite);
		ImageView answer = (ImageView) page1.findViewById(R.id.but_answer);
		//ImageView see = (ImageView) page1.findViewById(R.id.but_see);
		//msg.setOnClickListener(this);
		calendar.setOnClickListener(this);
		invite.setOnClickListener(this);
		//see.setOnClickListener(this);
		
		ImageView alarm = (ImageView) page2.findViewById(R.id.but_alarm);
		
		ImageView nowPos = (ImageView) page2.findViewById(R.id.but_reprotPos);
		
		alarm.setOnClickListener(this);
		answer.setOnClickListener(this);
		nowPos.setOnClickListener(this);
		
		ViewsPagerAdapter pagerAdapter = new ViewsPagerAdapter(menuViews);
		
		mMenuPager.setAdapter(pagerAdapter);
		
		mMenuBg.setVisibility(View.GONE);
		mMenuBg.setOnClickListener(this);
		mMenu.setOnClickListener(this);
		
		mUpAnim = AnimationUtils.loadAnimation(this, R.anim.move_up);
		//mUpAnim2 = AnimationUtils.loadAnimation(this, R.anim.move_up_from_half);
		//mMenu.setVisibility(View.GONE);
		/* views for popmenu end */
		retrieveDeviceListData();
		loaded = false;
		
		buildCard();
	}
	
	private final int MSG_LOADING_TIMEOUT = 121;
	
	private Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case MSG_LOADING_TIMEOUT:{
				loadingFinish();
			}
			break;
			}
		}
	};
	
	public boolean refreshList(){
		long upTime = mApp.getDataManager().checkRequestTime(DataManager.F_DEVICELIST);
		long curMs = System.currentTimeMillis();
		if((curMs - upTime) < 1000 * 60 * 2){
			return false;
		}
		return mApp.getDataManager().refreshData(DataManager.F_DEVICELIST);
	}
	
	private boolean refreshDeviceList(){
		String[] args = new String[2];
		args[0] = "DEV_SINGLE_TYPE";
		args[1] = new String(DEV_DATA.TYPE_LOCATE);
		JSONObject devjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICELIST, args);
		if(devjson != null){
			try{
				JSONArray ar = devjson.getJSONArray("array");
				int len = ar.length();
				if((len == 0) && (mDevListData.size() == 0)){
					return false;
				}else{
					ArrayList<DEV_DATA> backup = mDevListData;
					mDevListData = new ArrayList<DEV_DATA>();
					retrieveDeviceListData();
					if(compare(backup, mDevListData)){
						//String[] tids = getTIDS(mDevListData);
						//if(tids != null){
						//mApp.getDataManager().setUserData(DataManager.F_DEVICEFACE, tids);
						//mApp.getDataManager().refreshData(DataManager.F_DEVICEFACE);
						//}
						loaded = false;
						buildCard();
						startLoading();
						backup.clear();
						return true; // rebuild
					}else{
						backup.clear();
						updateFragmentArgs();
					}
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		return false;
	}
	
	private String[] getTIDS(ArrayList<DEV_DATA> list){
		if(list == null)
			return null;
		
		int size = list.size();
		if(size == 0)
			return null;
		
		String[] ret = new String[size];
		int pos = 0;
		for(DEV_DATA d:list){
			ret[pos] = new String(d.id);
			pos ++;
		}
		return ret;
	}
	
	private boolean compare(ArrayList<DEV_DATA> one, ArrayList<DEV_DATA> two){
		if(one.size() != two.size())
			return true;
		
		int size = one.size();
		for(int i = 0; i <size; i++){
			DEV_DATA d1 = one.get(i);
			DEV_DATA d2 = two.get(i);
			if(d1.id.equals(d2.id)){
				continue;
			}else{
				return true;
			}
		}
		return false;
	}
	
	private void updateFragmentArgs(){
		int size = mDevListData.size();
		mName.setText(mCurDev.name);
		for(DEV_DATA d:mDevListData){
			CardFragment f = mFragmentMap.get(d.id);
			if(f != null){
				Bundle args = new Bundle();
				args.putInt("total", size);
				args.putSerializable("dev", d);
				f.updateArgs(args);
			}
		}
	}
	
	private void retrieveDeviceListData(){
		String[] args = new String[2];
		args[0] = "DEV_SINGLE_TYPE";
		args[1] = new String(DEV_DATA.TYPE_LOCATE);
		JSONObject devjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICELIST, args);
		if(devjson != null){
			try{
				JSONArray ar = devjson.getJSONArray("array");
				int len = ar.length();
				boolean found = false;
				
				mDevListData.clear();
				int index = 0;
				for(int i = 0; i < len; i++){
					JSONObject e = ar.getJSONObject(i);
					DEV_DATA d = new DEV_DATA();
					d.id = e.getString("tid");
					d.name = e.getString("name");
						
					String ss = e.getString("status");
					d.status = Integer.parseInt(ss);
						
					d.type = e.getString("type");
						
					String a = e.getString("admin");
					d.admin = Integer.parseInt(a);
						
					d.index = index;
						
					mDevListData.add(d);
					if(mCurDev.id.equals(d.id)){
						found = true;
						mCurDev.index = d.index;
						mCurDev.name = d.name;
					}
					index ++;
				}
				if(mDevListData.size() > 0){
					if(!found){
						mCurDev = mDevListData.get(0);
						SharedPreferences p = getSharedPreferences(SettingsConstants.GENERAL_SETTING, MODE_PRIVATE);
						Editor e = p.edit();
						e.putString(SettingsConstants.KEY_CARD_VIEW_TID, mCurDev.id);
						e.commit();
					}
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	
	private void buildCard(){
		if(mName == null)
			return;
		int size = mDevListData.size();
		if(size <= 0){
			mName.setText(R.string.no_locate_dev);
			mSlider.setVisibility(View.GONE);
			mInvokeMenu.setVisibility(View.INVISIBLE);
			return;
		}
		mName.setText(mCurDev.name);
		
		if(loaded){	
			mPages.clear();
			mFragmentMap.clear();
			mSlider.setVisibility(View.VISIBLE);
			for(DEV_DATA d:mDevListData){
				CardFragment one = new CardFragment(mApp);
				Bundle args = new Bundle();
				
				args.putInt("total", size);
				args.putSerializable("dev", d);
				one.setArguments(args);
				mPages.add(one);
				mFragmentMap.put(d.id, one);
				if(d.id.equals(mCurDev.id)){
					one.queryLocationAndPower(mCurDev.id, false);
				}
			}
			mAdapter.notifyDataSetChanged();
			mInvokeMenu.setVisibility(View.VISIBLE);		
			mSlider.setCurrentItem(mCurDev.index);
		}else{
			mPages.clear();
			mFragmentMap.clear();
			mInvokeMenu.setVisibility(View.INVISIBLE);
			mSlider.setVisibility(View.GONE);
		}
	}
	
	
	private void loadingFinish(){
		loaded = true;
		mhandler.removeMessages(MSG_LOADING_TIMEOUT);
		mLoadingProgress.setVisibility(View.GONE);
		buildCard();
	}
	
	private void startLoading(){
		long upTime = mApp.getDataManager().checkRequestTime(DataManager.F_DEVICE_SETTINGS);
		long curMs = System.currentTimeMillis();
		if((curMs - upTime) < 1000 * 60 * 1){
			loadingFinish();
			return;
		}
		int size = mDevListData.size();
		if(size > 0){
			String[] args = new String[size];
			for(int i = 0; i< size; i++){
				DEV_DATA d = mDevListData.get(i);
				args[i] = new String(d.id);
			}
			
			mApp.getDataManager().setUserData(DataManager.F_DEVICE_SETTINGS, args);
			if(mApp.getDataManager().refreshData(DataManager.F_DEVICE_SETTINGS)){
				mLoadingProgress.setVisibility(View.VISIBLE);
				mLoadingProgress.setMax(size);
				mLoadingProgress.setProgress(0);
				//refresh.setVisibility(View.INVISIBLE);
				mhandler.removeMessages(MSG_LOADING_TIMEOUT);
				Message m = mhandler.obtainMessage(MSG_LOADING_TIMEOUT);
				mhandler.sendMessageDelayed(m, 30 * 1000);
				return;
			}
		}
		loadingFinish();
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(DataManager.DATA_UPDATE_ACTION)){
				String t = intent.getStringExtra("type");
				boolean s = intent.getBooleanExtra("state", false);				
				logd("onReceive:"+t+";"+s);
				if(t.equals(DataManager.F_DEVICE_LOCATION)){
					String tid = intent.getStringExtra("tid");
					if(tid.isEmpty())
						return;
					
					CardFragment cf = mFragmentMap.get(tid);
					if(cf != null)
						cf.refreshResult(t,s);
				}else if(t.equals(DataManager.F_DEVICE_POWER)){
					String tids = intent.getStringExtra("tidarr");
					try {
						JSONArray tidarr = new JSONArray(tids);
						int len = tidarr.length();
						for(int i = 0; i < len; i++){
							String tid = tidarr.getString(i);
							CardFragment cf = mFragmentMap.get(tid);
							if(cf != null)
								cf.refreshResult(t,s);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else if(t.equals(DataManager.F_DEVICELIST)){
					boolean rebuild = false;
					if(s){
						rebuild = refreshDeviceList();
					}
					if(false == rebuild){
						CardFragment cf = mFragmentMap.get(mCurDev.id);
						if(cf != null)
						cf.refreshResult(DataManager.F_DEVICELIST,s);
					}
				}else if(t.equals(DataManager.F_DEVICEFACE)){
					String tid = intent.getStringExtra("tid");
					if(tid.isEmpty())
						tid = mCurDev.id;
					CardFragment cf = mFragmentMap.get(tid);
					if(cf != null)
					cf.refreshResult(t,s);
				}else if(t.equals(DataManager.F_DEVICE_SETTINGS)){
					String tid = intent.getStringExtra("tid");
					if(loaded == false){
						int max = mLoadingProgress.getMax();
						int pro = mLoadingProgress.getProgress();
						if(pro == max)
							return;
						
						pro += 1;
						mLoadingProgress.setProgress(pro);
						if(pro == max){
							loadingFinish();
						}
					}else{
						if(tid.isEmpty())
							tid = mCurDev.id;
						CardFragment cf = mFragmentMap.get(tid);
						if(cf != null)
						cf.refreshResult(t,s);
					}
				}
			}else if(action.equals(SENT_SMS_CMD_ACTION)){
				int ret = getResultCode();
				
				mApp.dismissWaiting();
				if(ret!=RESULT_OK){
					mApp.showAlertDialog(CardsActivity.this, R.string.sms_failed);
					
				}
			}
		}
	};
	
	@Override
	public void onSaveInstanceState(Bundle b){
		
	}
	
	@Override
	public void onResume(){
		super.onResume();
		IntentFilter filter = new IntentFilter();
		//filter.addAction(HealthApp.ACTION_SIGN_IN_OUT);
		filter.addAction(DataManager.DATA_UPDATE_ACTION);
		//filter.addAction(DataManager.DATA_COMMIT_RESULT);
		filter.addAction(SENT_SMS_CMD_ACTION);
		registerReceiver(mReceiver, filter);
		if(!loaded){
			startLoading();
		}else{
			refreshDeviceList();
		}
		//upateCard();
	}
	
	@Override
	public void onPause(){
		super.onPause();
		logd("onPause");
		unregisterReceiver(mReceiver);
		mhandler.removeMessages(MSG_LOADING_TIMEOUT);
		mApp.dismissWaiting();
	}
	
	@Override
	public void onDestroy(){
		SharedPreferences p = getSharedPreferences(SettingsConstants.GENERAL_SETTING, MODE_PRIVATE);
		Editor e = p.edit();
		e.putString(SettingsConstants.KEY_CARD_VIEW_TID, mCurDev.id);
		e.commit();
		mPages.clear();
		mFragmentMap.clear();
		super.onDestroy();
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
	   	
	   	if(keyCode == KeyEvent.KEYCODE_BACK){
	   		if(mMenuBg.getVisibility() != View.GONE){
	   			closeMenu();
	   		return true;
	   		}else if(curFragmentIsRefreshing()){
	   			stopRefreshing();
	   			return true;
	   		}
	   	}
	   	return super.onKeyDown(keyCode,event);
    }

	private boolean curFragmentIsRefreshing(){
		CardFragment cf = mFragmentMap.get(mCurDev.id);
		if(cf != null){
			return cf.isRefreshing();
		}
		return false;
	}
	
	private void stopRefreshing(){
		CardFragment cf = mFragmentMap.get(mCurDev.id);
		if(cf != null){
			cf.cancelRefresh();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		case R.id.set:{
			if(mDevListData.size()>0){
			mCurDev = mDevListData.get(mCurDev.index);
			Intent i = new Intent(this,SettingActivity.class);
			i.putExtra("from", "card");
			i.putExtra("dev", mCurDev);
			startActivityForResult(i, RESULT_CODE_CARD_SETTINGS);
			}
		}break;
	
		case R.id.menu_bg:{
			closeMenu();
		}break;
		
		/*menu item start*/
		case R.id.but_calendar:
		{
			mCurDev = mDevListData.get(mCurDev.index);
			Intent i = new Intent(this,ReminderActivity.class);
			i.putExtra("tid", mCurDev.id);
			if(mCurDev.admin == 1)
			    i.putExtra("isAdmin", true);
			else
				i.putExtra("isAdmin", false);
			startActivity(i);			
		}
		break;
		
		case R.id.but_invite:{
			String uri = HttpConf.getDeviceInterestUri(mCurDev.id, mCurDev.name);
			Intent i = new Intent(this,QRCodeActivity.class);
			i.putExtra("type", QRCodeActivity.TYPE_DEVICE);
			i.putExtra("uri", uri);
			i.putExtra("mid",-1);
			startActivity(i);
			closeMenu();
		}break;
		
		case R.id.but_answer:
		{
			sendSmsCmd(mCurDev.id, "<ZDJT>");	
		}
		break;
		
		case R.id.but_alarm:
		{
			sendSmsCmd(mCurDev.id,"<JHBJ>");	
		}
		break;
		
		case R.id.but_reprotPos:
		{
			sendSmsCmd(mCurDev.id,"<JSDW>");	
		}
		break;		
		/*menu item end*/
		}
	}
	
	private String getDevPhNumber(String tid){
		DEV_SET mSetData = null;
		
		String[] args = new String[1];
		args[0] = tid;
		
		DEV_SET[] data = (DEV_SET[]) mApp.getDataManager().checkData(DataManager.F_DEVICE_SETTINGS, args);
		if(data != null){
			mSetData =  data[0];
			return mSetData.mobile;
		}
		return null;
	} 
	
	private void sendSmsCmd(String tid, final String content){
		final String mobile = getDevPhNumber(mCurDev.id);
		if((mobile == null) || mobile.trim().isEmpty()){
			if(mCurDev.admin == 1){
				mApp.showConfirmDialog(this, getResources().getString(R.string.setPhoneFirst), new OnClickListener() {
					
					@Override
					public void onClick(View view) {
						if(view.getId() == R.id.alert_but1){
							Intent i = new Intent(CardsActivity.this,DeviceManagerEdit.class);
							i.putExtra("dev", mCurDev);
							startActivity(i);
						}
					}
				});	
			}else{
				mApp.showAlertDialog(this, R.string.noPhoneNumber);
			}
			return;
		}
		
		mApp.showConfirmDialog(this, getResources().getString(R.string.sms_hint), new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				
				if(view.getId() == R.id.alert_but1){
					SmsManager smsMagager = SmsManager.getDefault();  
			        
			        Intent i = new Intent(SENT_SMS_CMD_ACTION);  
					
					PendingIntent pi = PendingIntent.getBroadcast(CardsActivity.this, 1, i, PendingIntent.FLAG_ONE_SHOT);
			        smsMagager.sendTextMessage(mobile, null, content, pi, null);

			        mApp.showWaitting(CardsActivity.this, null);
				}
			}
		});		
	}
	
	private int RESULT_CODE_CARD_SETTINGS = 33;
	@Override
	public void onActivityResult(int code, int ret, Intent intent){
		if(RESULT_CODE_CARD_SETTINGS == code){
			if(ret == RESULT_OK){
				String action = intent.getAction();
				if(action.equals("ACTIVATE_DEVICE_OK")){
					String tid = intent.getStringExtra("tid");
					mApp.getDataManager().refreshData(DataManager.F_DEVICE_SETTINGS, tid);
				}
			}
		}
	}
	
	private void closeMenu(){
		if(mMenuBg.getVisibility() != View.GONE){
			mMenuBg.setVisibility(View.GONE);
			mInvokeMenu.setVisibility(View.VISIBLE);
		}
	}
	
	private void invokeMenu(){
		
		if(curFragmentIsRefreshing())
			return;
		
		if(mMenuBg.getVisibility() == View.GONE){
			mMenuBg.setVisibility(View.VISIBLE);
			mMenu.startAnimation(mUpAnim);
			mUpAnim.setAnimationListener(new Animation.AnimationListener(){

				@Override
				public void onAnimationEnd(Animation arg0) {
					mMenu.clearAnimation();
					mInvokeMenu.setVisibility(View.INVISIBLE);
					//mMenuIndex.setCurrent(0);
					//mMenuIndex.update();
					//mMenuPager.setCurrentItem(0);
				}

				@Override
				public void onAnimationRepeat(Animation arg0) {}

				@Override
				public void onAnimationStart(Animation arg0) {}
			});
		}
	}
	
	private float menu_invoke_y = -1.0f;
	private long menu_invoke_time = -1;
	
	@Override
	public boolean onTouch(View v, MotionEvent e) {
		if(v.getId() == R.id.invoke_menu){
			if(e.getAction() == MotionEvent.ACTION_DOWN){
				//logd("action = " + e.getAction());
				menu_invoke_y = e.getY();
				menu_invoke_time = e.getEventTime();
			}else if(e.getAction() == MotionEvent.ACTION_MOVE){
				//logd("action = " + e.getAction());
				if(menu_invoke_y > 0){
					
					float y = e.getY();
					float minspace = 35.0f * getResources().getDisplayMetrics().density;
					//logd("(menu_invoke_y - y) = " + "(" + menu_invoke_y + "-" + y + ") = " + (menu_invoke_y - y));
					//logd("minspace = "+ minspace);
					if((menu_invoke_y - y) >= minspace){
						//logd("invokemenu");
						long t = e.getEventTime();
						if((t - menu_invoke_time) < 300){
							invokeMenu();
							menu_invoke_y = -1.0f;
						}
					}
					//menu_invoke_y = y;
				}
			}else if((e.getAction() == MotionEvent.ACTION_UP) || (e.getAction() == MotionEvent.ACTION_CANCEL)){
				//logd("action = " + e.getAction());
				menu_invoke_y = -1.0f;
				//if((menu_level == 0) && (e.getAction() == MotionEvent.ACTION_UP))
				//	invokeMenu(1);
			}
		}
		return true;
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
//		logd("onPageScrollStateChanged");
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
//		logd("onPageScrolled");
	}

	@Override
	public void onPageSelected(int pos) {
		CardFragment old_cf = mFragmentMap.get(mCurDev.id);
		old_cf.focusChange(false);
		mCurDev = mDevListData.get(pos);
		mName.setText(mCurDev.name);
		CardFragment cf = mFragmentMap.get(mCurDev.id);
		cf.focusChange(true);
	}
}
